import { useState, useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { Table, Button, Space, Tag, Modal, message, Input, Card, Tooltip, Image, Tabs } from 'antd'
import { EyeOutlined, CheckOutlined, CloseOutlined, DownloadOutlined } from '@ant-design/icons'
import { fetchPendingNotes, reviewNote } from '@/store/slices/auditSlice'
import './index.scss'

const { TextArea } = Input

const NoteManagement = () => {
  const dispatch = useDispatch()
  const { noteList, loading } = useSelector((state) => state.audit)
  
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [detailVisible, setDetailVisible] = useState(false)
  const [currentNote, setCurrentNote] = useState(null)
  const [rejectVisible, setRejectVisible] = useState(false)
  const [rejectReason, setRejectReason] = useState('')
  const [activeTab, setActiveTab] = useState('all')
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)

  // 加载笔记列表
  useEffect(() => {
    dispatch(fetchPendingNotes({ page, size: pageSize }))
  }, [dispatch, page, pageSize])

  // 模拟数据（作为后备）
  const [dataSource, setDataSource] = useState([
    {
      id: 1,
      bookName: '活着',
      bookCover: 'https://images.unsplash.com/photo-1544947950-fa07a98d237f?w=100',
      userName: '张三',
      content: '这本书让我深刻理解了生命的意义，福贵的一生虽然充满苦难，但他始终保持着对生活的热爱...',
      fullContent: '这本书让我深刻理解了生命的意义，福贵的一生虽然充满苦难，但他始终保持着对生活的热爱。余华用朴实的语言描绘了一个时代的变迁，让人感慨万千。',
      images: ['https://images.unsplash.com/photo-1544947950-fa07a98d237f?w=300'],
      status: 'pending',
      createTime: '2024-01-20 10:30:00',
      likes: 45,
      comments: 12,
    },
    {
      id: 2,
      bookName: '百年孤独',
      bookCover: 'https://images.unsplash.com/photo-1512820790803-83ca734da794?w=100',
      userName: '李四',
      content: '马尔克斯的魔幻现实主义手法令人叹为观止，布恩迪亚家族的兴衰史映射了整个拉美的历史...',
      fullContent: '马尔克斯的魔幻现实主义手法令人叹为观止，布恩迪亚家族的兴衰史映射了整个拉美的历史。孤独是这本书的主题，每个人物都在寻找着什么，却又失去着什么。',
      images: [],
      status: 'approved',
      createTime: '2024-01-19 15:20:00',
      likes: 89,
      comments: 23,
    },
    {
      id: 3,
      bookName: '三体',
      bookCover: 'https://images.unsplash.com/photo-1589998059171-988d887df646?w=100',
      userName: '王五',
      content: '刘慈欣构建的宇宙观令人震撼，黑暗森林法则让我重新思考人类文明在宇宙中的位置...',
      fullContent: '刘慈欣构建的宇宙观令人震撼，黑暗森林法则让我重新思考人类文明在宇宙中的位置。这不仅是一部科幻小说，更是对人性和文明的深刻思考。',
      images: ['https://images.unsplash.com/photo-1589998059171-988d887df646?w=300', 'https://images.unsplash.com/photo-1516979187457-637abb4f9353?w=300'],
      status: 'pending',
      createTime: '2024-01-18 09:15:00',
      likes: 156,
      comments: 45,
    },
    {
      id: 4,
      bookName: '平凡的世界',
      bookCover: 'https://images.unsplash.com/photo-1524995997946-a1c2e315a42f?w=100',
      userName: '赵六',
      content: '路遥笔下的陕北农村生活真实而感人，孙少平的奋斗历程激励着每一个平凡人...',
      fullContent: '路遥笔下的陕北农村生活真实而感人，孙少平的奋斗历程激励着每一个平凡人。这本书告诉我们，即使在平凡的世界里，也可以活出不平凡的人生。',
      images: [],
      status: 'rejected',
      rejectReason: '内容过于简短，缺乏深度分析',
      createTime: '2024-01-17 14:45:00',
      likes: 23,
      comments: 8,
    },
  ])

  // 状态标签配置
  const statusConfig = {
    pending: { text: '待审核', color: 'orange' },
    approved: { text: '已通过', color: 'green' },
    rejected: { text: '已拒绝', color: 'red' },
  }

  // 查看详情
  const handleViewDetail = (record) => {
    setCurrentNote(record)
    setDetailVisible(true)
  }

  // 通过审核
  const handleApprove = async (record) => {
    Modal.confirm({
      title: '确认通过',
      content: `确定通过用户"${record.userName}"的笔记吗？`,
      onOk: async () => {
        try {
          await dispatch(reviewNote({ 
            id: record.id, 
            data: { status: 'approved' } 
          })).unwrap()
          message.success('审核通过')
          // 重新加载列表
          dispatch(fetchPendingNotes({ page, size: pageSize }))
        } catch (error) {
          message.error(error?.message || '审核失败')
        }
      },
    })
  }

  // 拒绝审核
  const handleReject = (record) => {
    setCurrentNote(record)
    setRejectVisible(true)
  }

  // 确认拒绝
  const confirmReject = async () => {
    if (!rejectReason.trim()) {
      message.warning('请输入拒绝原因')
      return
    }
    
    try {
      if (currentNote?.isBatch) {
        // 批量拒绝
        await Promise.all(
          selectedRowKeys.map(id =>
            dispatch(reviewNote({ 
              id, 
              data: { status: 'rejected', reason: rejectReason } 
            })).unwrap()
          )
        )
        setSelectedRowKeys([])
        message.success(`已拒绝 ${selectedRowKeys.length} 条笔记`)
      } else {
        // 单个拒绝
        await dispatch(reviewNote({ 
          id: currentNote.id, 
          data: { status: 'rejected', reason: rejectReason } 
        })).unwrap()
        message.success('已拒绝该笔记')
      }
      
      // 重新加载列表
      dispatch(fetchPendingNotes({ page, size: pageSize }))
    } catch (error) {
      message.error(error?.message || '操作失败')
    }
    
    setRejectVisible(false)
    setRejectReason('')
  }

  // 批量通过
  const handleBatchApprove = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要审核的笔记')
      return
    }
    Modal.confirm({
      title: '批量通过',
      content: `确定通过选中的 ${selectedRowKeys.length} 条笔记吗？`,
      onOk: async () => {
        try {
          await Promise.all(
            selectedRowKeys.map(id =>
              dispatch(reviewNote({ 
                id, 
                data: { status: 'approved' } 
              })).unwrap()
            )
          )
          setSelectedRowKeys([])
          message.success('批量审核通过')
          // 重新加载列表
          dispatch(fetchPendingNotes({ page, size: pageSize }))
        } catch (error) {
          message.error(error?.message || '批量审核失败')
        }
      },
    })
  }

  // 批量拒绝
  const handleBatchReject = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要拒绝的笔记')
      return
    }
    setRejectVisible(true)
    setCurrentNote({ isBatch: true })
  }

  // 导出数据
  const handleExport = () => {
    message.success('开始导出数据')
  }

  // 使用后端数据或模拟数据
  const actualDataSource = noteList.length > 0 ? noteList : dataSource

  // 根据Tab筛选数据
  const filteredData = actualDataSource.filter(item => {
    if (activeTab === 'all') return true
    return item.status === activeTab
  })

  // 统计各状态数量
  const getStatusCount = (status) => {
    if (status === 'all') return actualDataSource.length
    return actualDataSource.filter(item => item.status === status).length
  }

  // 处理分页变化
  const handleTableChange = (pagination) => {
    setPage(pagination.current)
    setPageSize(pagination.pageSize)
  }

  const columns = [
    {
      title: '图书',
      dataIndex: 'bookName',
      key: 'bookName',
      width: 200,
      render: (text, record) => (
        <div className="book-info">
          <Image
            src={record.bookCover}
            alt={text}
            width={50}
            height={70}
            style={{ objectFit: 'cover', borderRadius: 4 }}
          />
          <span className="book-name">{text}</span>
        </div>
      ),
    },
    {
      title: '用户',
      dataIndex: 'userName',
      key: 'userName',
      width: 100,
    },
    {
      title: '笔记内容',
      dataIndex: 'content',
      key: 'content',
      ellipsis: true,
      render: (text) => (
        <Tooltip title={text}>
          <div className="note-content">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={statusConfig[status].color}>
          {statusConfig[status].text}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 160,
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button
              type="link"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => handleViewDetail(record)}
            >
              详情
            </Button>
          </Tooltip>
          {record.status === 'pending' && (
            <>
              <Tooltip title="通过">
                <Button
                  type="link"
                  size="small"
                  icon={<CheckOutlined />}
                  style={{ color: '#52c41a' }}
                  onClick={() => handleApprove(record)}
                >
                  通过
                </Button>
              </Tooltip>
              <Button
                type="link"
                size="small"
                icon={<CloseOutlined />}
                danger
                onClick={() => handleReject(record)}
              >
                拒绝
              </Button>
            </>
          )}
        </Space>
      ),
    },
  ]

  const rowSelection = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
  }

  return (
    <div className="note-management-container">
      <Card className="table-card">
        <div className="tabs-header">
          <Tabs
            activeKey={activeTab}
            onChange={setActiveTab}
            className="status-tabs"
            items={[
              {
                key: 'all',
                label: `全部 (${getStatusCount('all')})`,
              },
              {
                key: 'pending',
                label: `待审核 (${getStatusCount('pending')})`,
              },
              {
                key: 'approved',
                label: `已通过 (${getStatusCount('approved')})`,
              },
              {
                key: 'rejected',
                label: `已拒绝 (${getStatusCount('rejected')})`,
              },
            ]}
          />
          <div className="tabs-actions">
            <Space>
              <Button
                type="primary"
                icon={<CheckOutlined />}
                onClick={handleBatchApprove}
                disabled={selectedRowKeys.length === 0 || activeTab !== 'pending'}
              >
                批量通过
              </Button>
              <Button
                danger
                icon={<CloseOutlined />}
                onClick={handleBatchReject}
                disabled={selectedRowKeys.length === 0 || activeTab !== 'pending'}
              >
                批量拒绝
              </Button>
              <Button icon={<DownloadOutlined />} onClick={handleExport}>
                导出数据
              </Button>
            </Space>
          </div>
        </div>

        {selectedRowKeys.length > 0 && (
          <div className="selection-bar">
            <span className="selection-info">
              已选择 {selectedRowKeys.length} 项
            </span>
          </div>
        )}

        <Table
          rowSelection={{
            ...rowSelection,
            getCheckboxProps: (record) => ({
              disabled: record.status !== 'pending',
            }),
          }}
          columns={columns}
          dataSource={filteredData}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1200 }}
          pagination={{
            current: page,
            pageSize: pageSize,
            total: filteredData.length,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            pageSizeOptions: ['10', '20', '50', '100']
          }}
          onChange={handleTableChange}
        />
      </Card>

      {/* 详情弹窗 */}
      <Modal
        title="笔记详情"
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailVisible(false)}>
            关闭
          </Button>,
          currentNote?.status === 'pending' && (
            <Button
              key="approve"
              type="primary"
              icon={<CheckOutlined />}
              onClick={() => {
                handleApprove(currentNote)
                setDetailVisible(false)
              }}
            >
              通过
            </Button>
          ),
          currentNote?.status === 'pending' && (
            <Button
              key="reject"
              danger
              icon={<CloseOutlined />}
              onClick={() => {
                setDetailVisible(false)
                handleReject(currentNote)
              }}
            >
              拒绝
            </Button>
          ),
        ]}
        width={700}
      >
        {currentNote && (
          <div className="note-detail">
            <div className="detail-item">
              <label>图书信息：</label>
              <div className="book-detail">
                <Image
                  src={currentNote.bookCover}
                  alt={currentNote.bookName}
                  width={80}
                  height={110}
                />
                <span>{currentNote.bookName}</span>
              </div>
            </div>
            <div className="detail-item">
              <label>用户：</label>
              <span>{currentNote.userName}</span>
            </div>
            <div className="detail-item">
              <label>笔记内容：</label>
              <div className="note-full-content">{currentNote.fullContent}</div>
            </div>
            {currentNote.images && currentNote.images.length > 0 && (
              <div className="detail-item">
                <label>配图：</label>
                <div className="note-images">
                  <Image.PreviewGroup>
                    {currentNote.images.map((img, index) => (
                      <Image
                        key={index}
                        src={img}
                        width={150}
                        height={150}
                        style={{ objectFit: 'cover', marginRight: 8 }}
                      />
                    ))}
                  </Image.PreviewGroup>
                </div>
              </div>
            )}
            <div className="detail-item">
              <label>互动数据：</label>
              <Space size="large">
                <span>👍 点赞 {currentNote.likes}</span>
                <span>💬 评论 {currentNote.comments}</span>
              </Space>
            </div>
            <div className="detail-item">
              <label>状态：</label>
              <Tag color={statusConfig[currentNote.status].color}>
                {statusConfig[currentNote.status].text}
              </Tag>
            </div>
            {currentNote.rejectReason && (
              <div className="detail-item">
                <label>拒绝原因：</label>
                <div className="reject-reason">{currentNote.rejectReason}</div>
              </div>
            )}
            <div className="detail-item">
              <label>创建时间：</label>
              <span>{currentNote.createTime}</span>
            </div>
          </div>
        )}
      </Modal>

      {/* 拒绝原因弹窗 */}
      <Modal
        title="拒绝笔记"
        open={rejectVisible}
        onOk={confirmReject}
        onCancel={() => {
          setRejectVisible(false)
          setRejectReason('')
        }}
        okText="确定"
        cancelText="取消"
      >
        <div style={{ marginBottom: 16 }}>
          <p>请输入拒绝原因：</p>
          <TextArea
            rows={4}
            value={rejectReason}
            onChange={(e) => setRejectReason(e.target.value)}
            placeholder="请详细说明拒绝的原因，以便用户改进..."
            maxLength={200}
            showCount
          />
        </div>
      </Modal>
    </div>
  )
}

export default NoteManagement
